(function(){
    var isEditStatus=false;
    var isEditGlobalEnv=false;
    var GLOBAL_ENV_ID="globalEnv";
    var envSelector;
    $(function(){
        new templateInclude(["/templates/environment.tmp"]);
        envSelector= new selector({selector:$("#envSelector"),
            onChange:function(event){
                var href=event.selectedHref;
                if(href=='#manage'){
                    var environmentDialog = new dialog({
                        title:"管理环境",
                        content:template("manageEnvironmentTpl",{}),
                        isConfirm:true,
                        onOk:function(){
                            if(isEditStatus){
                                var valid = new validator({validateTarget:$("#manageEnvironment")});
                                var result = valid.validate();
                                if(!result.result){
                                    var errorDialog = new dialog({
                                        content:result.tip
                                    })
                                    errorDialog.open();
                                }else{
                                    var envName = $("#manageEnvironment").find("input[name='envName']").val();
                                    var id = $("#manageEnvironment").find("input[name='id']").val();
                                    var pair = $("#manageEnvironment").find("div[data='pair']");
                                    var envEntities = [];
                                    pair.each(function(){
                                        var item = $(this);
                                        var entity={};
                                        entity[item.find("input[name='key']").val()]=item.find("input[name='value']").val();
                                        envEntities.push(entity);
                                    });
                                    if(envEntities.length>0) {
                                        var envContext = {};
                                        envContext.envName = envName;
                                        envContext.items=envEntities;
                                        envContext.id=id;
                                        smtPost.saveEnv(envContext,function(data){
                                               if(data.status){
                                                   var successDialog = new dialog({
                                                       title:"提示",
                                                       content:"操作成功！",
                                                       onOk:function(){
                                                           if(smtPost.refreshFun){
                                                               smtPost.refreshFun();
                                                           }
                                                       }
                                                   });
                                                   successDialog.open();
                                                   $("#addEnvironmentBackButton").click();
                                                   loadEnvData();
                                               }else{
                                                   var errorDialog = new dialog({
                                                       content:data.error,
                                                       onOk:function(){
                                                           if(smtPost.refreshFun){
                                                               smtPost.refreshFun();
                                                           }
                                                       }
                                                   });
                                                   errorDialog.open();
                                               }
                                        });

                                    }else{
                                        $("#addEnvironmentBackButton").click();
                                    }
                                }
                            }else{
                                environmentDialog.close();
                            }
                        }
                    })
                    environmentDialog.open();
                    loadEnvData();
                    $("#addNewEnvironment").bind("click",function(){
                        createEditEnvironmentView({});
                    });
                    $("#addGlobalEnvironment").bind("click",function(){
                        var globalEnv = smtPost.getEnvDetial(GLOBAL_ENV_ID);
                        if(!globalEnv){
                            globalEnv={};
                        }
                        globalEnv.envName=GLOBAL_ENV_ID;
                        globalEnv.id=GLOBAL_ENV_ID;
                        createEditEnvironmentView(globalEnv);
                    });
                    return false;
                }
                return true;
            }});

    });

    var loadEnvData=function(){
        var html='';
        for(var pro in env){
            if(env[pro].id==GLOBAL_ENV_ID){
                continue;
            }
            html+=template("envListItemTpl",env[pro]);
        }
        $("#envListTable").html(html);
        $(".editEnv").bind("click",function(){
            var me = $(this);
            var id=me.attr("data");
            createEditEnvironmentView(smtPost.getEnvDetial(id));
        });
        $(".removeEnv").bind("click",function(){
            var me = $(this);
            var confirmDialog=new dialog({
                title:"确认是否删除",
                content:"是否执行删除操作？",
                isConfirm:true,
                onOk:function(){
                    confirmDialog.close();
                    var id=me.attr("data");
                    me.parents("tr").fadeOut();
                    me.parents("tr").remove();
                    smtPost.removeEnv(id);
                }
            });
            confirmDialog.open();
        });
        $(".copyEnv").bind("click",function(){
            var me = $(this);
            var id=me.attr("data");
            var originEnv = smtPost.getEnvDetial(id);
            var newEnv = {};
            newEnv.envName=originEnv.envName+"copy";
            newEnv.items = originEnv.items;
            smtPost.saveEnv(newEnv);
            loadEnvData();
        });
        rendingEnvSelector();
    }

    window.rendingEnvSelector=function(){
        var html='';
        for(var pro in env){
            if(env[pro].id==GLOBAL_ENV_ID){
                continue;
            }
            html+=template("envSelectorTpl",env[pro]);
        }
        $("#envSelector").find(".divider").find("~li").remove();
        $("#envSelector").find(".divider").after(html);
        envSelector.rebindEvent();
    }

    var createEditEnvironmentView=function(data){
        $("#environmentContainer").slideUp();
        $("#manageEnvironment").html(template("editEnvironmentTpl",data));
        $("#manageEnvironment").slideDown();
        isEditStatus=true;
        $("#addEnvironmentBackButton").bind("click",function(){
            $("#environmentContainer").slideDown();
            $("#manageEnvironment").slideUp();
            isEditStatus=false;
        });
        bindAddKV();
    }
})();